<template>
  <div>
    <div class="zhuangtai">
      <el-select
        v-model="value"
        :placeholder="selectPlaceholder"
        clearable
        style="width: 300px"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
    </div>
    <div class="block">
      <el-date-picker
        v-model="value2"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
      >
      </el-date-picker>
    </div>
    <div class="fanghao">
      <el-input v-model="input" placeholder="房号"></el-input>
    </div>
    <div class="sousuo">
      <el-button
        type="primary"
        icon="el-icon-search"
        style="width: 100px"
        @click="search"
        >{{ searchBtnText }}</el-button
      >
    </div>
    <el-tabs
      type="border-card"
      style="margin-top: 20px"
      @tab-click="handleTabChange"
      v-model="active"
    >
      <el-tab-pane label="智能设备" name="smart">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="communityname" label="单元名称" width="180">
          </el-table-column>
          <el-table-column prop="buildnum" label="幢号" width="180">
          </el-table-column>
          <el-table-column prop="homenum" label="房号"> </el-table-column>
          <el-table-column prop="homename" label="房主"> </el-table-column>
          <el-table-column prop="airnum" label="空调"> </el-table-column>
          <el-table-column prop="wifiname" label="Wi-Fi"> </el-table-column>
          <el-table-column prop="washnum" label="洗衣机"> </el-table-column>
          <el-table-column prop="createtime" label="授予时间">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createtime) }}
            </template>
          </el-table-column>
          <el-table-column prop="smartstatus" label="状态">
            <template slot-scope="scope">
              {{ scope.row.smartstatus === 1 ? "完好" : "待维修" }}
            </template>
          </el-table-column>
          <el-table-column label="操作状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.smartstatus"
                :active-value="1"
                :inactive-value="2"
                @change="handleStatusChange(scope.row, $event)"
              >
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="current"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="page"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="家居设备" name="home">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="communityname" label="单元名称" width="180">
          </el-table-column>
          <el-table-column prop="buildnum" label="幢号" width="180">
          </el-table-column>
          <el-table-column prop="homenum" label="房号"> </el-table-column>
          <el-table-column prop="homename" label="房主"> </el-table-column>
          <el-table-column prop="homedesk" label="书桌"> </el-table-column>
          <el-table-column prop="homechair" label="椅子"> </el-table-column>
          <el-table-column prop="homeclothes" label="衣柜"> </el-table-column>
          <el-table-column prop="createtime" label="授予时间">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createtime) }}
            </template>
          </el-table-column>
          <el-table-column prop="smartstatus" label="状态">
            <template slot-scope="scope">
              {{ scope.row.familystatus === 1 ? "完好" : "待维修" }}
            </template>
          </el-table-column>
          <el-table-column label="操作状态">
            <template slot-scope="scope">
              <el-tooltip :content="'Switch value: ' + value" placement="top">
                <el-switch
                  v-model="scope.row.familystatus"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-value="1"
                  :inactive-value="2"
                  @change="handleStatusChange1(scope.row, $event)"
                >
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="current"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="page"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
export default {
  data() {
    return {
      searchBtnText: "查询",
      active: "smart",
      selectPlaceholder: "智能设备状态",
      button: false,
      tableData: [],
      options: [
        {
          value: "1",
          label: "完好",
        },
        {
          value: "2",
          label: "待维修",
        },
      ],
      value: "",
      value2: "",
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      input: "",
      current: 1,
      page: 10,
      total: 0,
    };
  },
  methods: {
    async indexlist() {
      let res = await this.$axios.get(
        `http://community.byesame.com/house/searchdeviceList?smartstatus=&familystatus=&homenum=&startDate=&endDate=&currPage=${
          this.current - 1
        }&pageNum=${
          this.page
        }&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI1NzQwLCJleHAiOjE3NjE2MTIxNDB9.65of_2PJ9pyD8NF0fW8w0RlWVn2M-eQbo97HzMOTfIA`
      );
      console.log(res);
      this.tableData = res.data.data;
      this.total = res.data.total;
    },
    formatDate(rawTime) {
      // 1. 处理空值：如果没有时间，返回“暂无”
      if (!rawTime) return "暂无";

      // 2. 创建 Date 对象（兼容时间戳、字符串格式）
      const date = new Date(rawTime);

      // 3. 处理无效时间（如格式错误）
      if (isNaN(date.getTime())) return "格式错误";

      // 4. 提取年、月、日（月和日补零，确保格式统一，如 09 而非 9）
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从 0 开始，需 +1
      const day = String(date.getDate()).padStart(2, "0");
      const hour = String(date.getHours()).padStart(2, "0");
      const minute = String(date.getMinutes()).padStart(2, "0");
      const second = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    handleTabChange(tab) {
      if (tab.name === "smart") {
        this.selectPlaceholder = "智能设备状态";
        this.searchBtnText = "查询";
      } else if (tab.name === "home") {
        this.selectPlaceholder = "家居设备状态";
        this.searchBtnText = "搜索";
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.page = val;
      this.current = 1;
      this.indexlist();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current = val;
      this.indexlist();
    },
    async handleStatusChange(row, newStatus) {
      // 1. 保存“旧状态”（取消时要恢复用）
      const oldStatus = newStatus === 1 ? 2 : 1;

      try {
        // 2. 弹出确认框
        await this.$confirm(
          `确定要将状态改为${newStatus === 1 ? "完好" : "待维修"}吗?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        // 3. 点击“确定”：调用接口提交新状态
        const res = await this.$axios.post(
          "http://community.byesame.com/house/updatesmartStatus",
          {
            id: row.id,
            smartstatus: newStatus, // 用新状态提交
            token:
              "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI1NzQwLCJleHAiOjE3NjE2MTIxNDB9.65of_2PJ9pyD8NF0fW8w0RlWVn2M-eQbo97HzMOTfIA",
          }
        );

        // 4. 接口成功：提示更新成功
        console.log(res);
        this.$message({ type: "success", message: "状态更新成功!" });
      } catch (error) {
        // 5. 点击“取消”或接口失败：回滚到旧状态
        row.smartstatus = oldStatus;
        // 区分是“用户取消”还是“接口失败”
        if (error.name === "Cancel") {
          this.$message({ type: "info", message: "已取消更新" });
        } else {
          this.$message({ type: "error", message: "更新失败，请重试" });
        }
      }
    },
    async handleStatusChange1(row, newStatus) {
      // 1. 保存“旧状态”（取消时要恢复用）
      const oldStatus = newStatus === 1 ? 2 : 1;

      try {
        // 2. 弹出确认框
        await this.$confirm(
          `确定要将状态改为${newStatus === 1 ? "完好" : "待维修"}吗?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        // 3. 点击“确定”：调用接口提交新状态
        const res = await this.$axios.post(
          "http://community.byesame.com/house/updatefamilyStatus",
          {
            id: row.id,
            familystatus: newStatus, // 用新状态提交
            token:
              "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI1NzQwLCJleHAiOjE3NjE2MTIxNDB9.65of_2PJ9pyD8NF0fW8w0RlWVn2M-eQbo97HzMOTfIA",
          }
        );

        // 4. 接口成功：提示更新成功
        console.log(res);
        this.$message({ type: "success", message: "状态更新成功!" });
      } catch (error) {
        // 5. 点击“取消”或接口失败：回滚到旧状态
        row.familyStatus = oldStatus;
        // 区分是“用户取消”还是“接口失败”
        if (error.name === "Cancel") {
          this.$message({ type: "info", message: "已取消更新" });
        } else {
          this.$message({ type: "error", message: "更新失败，请重试" });
        }
      }
    },
    async search() {
      let res = await this.$axios.get(
        `http://community.byesame.com/house/searchdeviceList?smartstatus=${this.value}&familystatus=&homenum=${this.input}&startDate=${this.value2}&endDate=&currPage=0&pageNum=10&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI1NzQwLCJleHAiOjE3NjE2MTIxNDB9.65of_2PJ9pyD8NF0fW8w0RlWVn2M-eQbo97HzMOTfIA`
      );
      console.log(res);
      this.tableData = res.data.data;
      this.total = res.data.total;
    },

    // 保留原来的indexlist方法（不变）
  },
  created() {
    this.indexlist();
  },
};
</script>
<style scoped>
.zhuangtai {
  display: inline-block;
}
.block {
  display: inline-block;
  margin-left: 10px;
}
.fanghao {
  width: 300px;
  display: inline-block;
  margin-left: 10px;
}
.sousuo {
  display: inline-block;
  margin-left: 10px;
}
</style>